/* eslint-disable indent */
/* eslint-disable @typescript-eslint/indent */
import React, { useMemo, useCallback, useState } from 'react';
import PropTypes from 'prop-types';
import { Icon, Modal, Typography, Checkbox, Divider } from 'antd';
import * as d3 from 'd3';
import { Avatar } from '@/pages/Organization/OrgFlow/components';
import cn from 'classnames';
import OrganizationModal from '@/pages/Organization/OrgFlow/components/OrganizationModal/OrganizationModal';
import { orgDeleteCheck } from '@/pages/Organization/OrgFlow/services';
import authHelper from '@/utils/auth/helper';
import { eventTrack } from '@/utils/track';
import { useMount } from 'react-use';
import defaultAvatar from '@/assets/orgTree_userAvatar.png';
// import Organization from '../../components/Organization';
import { NODE_SIZE, ORIENTATION, VERTICAL_CONFIG, HORIZONTAL_CONFIG } from '../constant';

import styles from './index.less';

const { Text } = Typography;
const { checkCode } = authHelper;
const Node = ({
    nodeData,
    control,
    treeId,
    onlyTree, // 审批的场景会要求只显示机构的数据, 其他数据能不要就不要
    orientation,
    onAddCompany,
    onAddDepartment,
    onDelete,
    onCollapseEmployeesNode,
    onCollapseLeftNode,
    onCollapseRightNode,
    orgColorMap,
    onFocusNode,
    onClickJobDuty,
    // onClickJobRank,
    onClickOrganizationModal
}) => {
    const {
        organizationPermissions,
        organizationType,
        organizationName,
        organizationCode,
        organizationPath,
        // employeeNum = 0,
        allEmployeeNum = 0,
        leaderEmployees = [],
        employees = [],
        employeeVisible,
        auditStatus,
        deleted = false,
        append = false,
        leftNode,
        rightNode,
        colorCode,
        leaderDutyAlias,
        leaderDutyAuditStatus
    } = nodeData.data;
    const { x, y, depth } = nodeData;
    const modalRef = React.useRef(null);
    const organizationTypeDict = ['', '集团', '公司', '部门'];
    const isShowModal = !onlyTree && !control && organizationCode;

    const [showTips, setShowTips] = useState(false);
    const getNodeColorCode = useCallback(
        item => colorCode || orgColorMap?.[item?.administrativeOrganizationCode]?.colorCode || '#aaa',
        [colorCode, orgColorMap]
    );

    // mounted 绘制额外内容, 一次更新绘制一次
    useMount(() => {
        // eslint-disable-next-line no-underscore-dangle
        const hasChildren = nodeData.children?.length > 0 || nodeData._children?.length > 0;

        // 绘制根节点收缩情况下的连线
        const drawRootLine = () => {
            if (depth === 0 && hasChildren) {
                d3.selectAll(`#${treeId} .rd3t-tree-container > svg >g path.rootLine`).remove();
                const svg = d3.select(`#${treeId} .rd3t-tree-container > svg > g`);
                svg.insert('path', '.nodeBase')
                    .attr('class', 'rootLine')
                    .attr(
                        'd',
                        orientation === ORIENTATION.VERTICAL
                            ? `M0 ${VERTICAL_CONFIG.shapePoint.x} v15`
                            : `M${HORIZONTAL_CONFIG.shapePoint.x - 18} 0 h18`
                    );
            }
        };

        // 绘制删除状态的虚线
        const drawDasharrayLine = () => {
            const { id, data: node } = nodeData;
            const line = document.querySelector(`#${treeId} [data-target-id="${id}"]`);
            if (node.deleted && line) {
                line.setAttribute('stroke-dasharray', '5, 5');
            }
        };

        // 绘制助理团的线
        const drawAgentManagementLine = () => {
            const { relateOrganizationCodes: agentManagement = [] } = nodeData.data;
            const svg = d3.select(`#${treeId} .rd3t-tree-container > svg > g`);
            // 每个节点逐个执行, 当执行根节点的时候清空上次绘制的线
            if (depth === 0) {
                d3.selectAll(`#${treeId} .rd3t-tree-container > svg g.agentBase`).remove();
            }

            if (agentManagement.length > 0) {
                agentManagement.forEach(code => {
                    const targetNode = document.querySelector(`#${treeId} [data-org-code=${code}]`);
                    if (svg && targetNode) {
                        // 获取目标节点的X坐标
                        const tX = targetNode.getAttribute('data-x');
                        // const tY = targetNode.getAttribute('data-y');

                        // console.log('方向 :>> ', orientation === ORIENTATION.VERTICAL ? '纵向' : '横向');
                        // console.log(`被关联机构: ${targetNode.getAttribute('data-org-name')} Tx :>> `, tX, tY);
                        // console.log(`助理团: ${organizationName} x:>> `, x, y);

                        // 绘制组
                        const g = svg
                            .insert('g', '.nodeBase')
                            .attr('class', 'agentBase')
                            .attr(
                                'transform',
                                orientation === ORIENTATION.VERTICAL
                                    ? `translate(${tX > x ? tX : x},${y})`
                                    : `translate(${y + 12},${tX > x ? x : x})`
                            );

                        // 绘制近点圆圈
                        // g.append('rect')
                        //     .attr('x', -5)
                        //     .attr('y', -5)
                        //     .attr('rx', 10)
                        //     .attr('ry', 10)
                        //     .attr('width', 10)
                        //     .attr('height', 10)
                        //     .attr('class', 'agentPoint')
                        //     .attr('fill', 'red');

                        // 绘制线
                        g.append('path')
                            .attr('class', 'nodeAgent')
                            // .attr('d', `M0, -${NODE_SIZE.y / 2} V60 H${tX > x ? x - tX : tX - x} V0`)
                            .attr(
                                'd',
                                orientation === ORIENTATION.VERTICAL
                                    ? `M0, -${NODE_SIZE.y / 2 - 1} h${tX > x ? x - tX : tX - x}`
                                    : `M0, 0 v${tX > x ? Math.abs(x - tX) : tX - x}`
                            );
                        // .attr('stroke-dasharray', '5, 5');

                        // 绘制远点圆圈
                        // g.append('rect')
                        //     .attr('x', tX > x ? x - tX + 5 : tX - x - 5)
                        //     .attr('y', -5)
                        //     .attr('rx', 10)
                        //     .attr('ry', 10)
                        //     .attr('width', 10)
                        //     .attr('height', 10)
                        //     .attr('class', 'agentPoint')
                        //     .attr('fill', 'red');
                    }
                });
            }
        };

        // 绘制'+' '-'的符号
        const drawNodeShape = () => {
            const { id, _collapsed } = nodeData;
            const nodeShape = document.querySelector(`#${treeId} [id="${id}"] .nodeShape > .shape`);
            if (nodeShape) {
                nodeShape.innerHTML = _collapsed ? '+' : '-';
            }
        };

        // 绘制员工
        const drawEmployees = async () => {
            const svg = d3.select(`#${treeId} .rd3t-tree-container > svg > g`);
            if (depth === 0) {
                d3.selectAll(`#${treeId} .rd3t-tree-container > svg g.employeesNode`).remove();
            }
            // 部门主管有多个时，把剩余的在下属那边展示出来，并带有主管标识
            const combineEmployees = [
                ...leaderEmployees.slice(1).map(item => {
                    // eslint-disable-next-line no-param-reassign
                    item.employeeName = `${item.employeeName} [主管]`;
                    return item;
                }),
                ...employees
            ];
            // 有员工才绘制
            if (hasChildren && combineEmployees.length > 0) {
                // +-符号
                const employeesNode = svg
                    .insert('g', '.nodeBase')
                    .attr('class', 'employeesNode')
                    .attr('data-employees-id', organizationCode)
                    .attr(
                        'transform',
                        `translate(${orientation === ORIENTATION.VERTICAL ? x + 75 : y + 75}, ${
                            orientation === ORIENTATION.VERTICAL ? y : x + NODE_SIZE.y / 2
                        })`
                    );

                // 链接+-符号的左侧线
                employeesNode
                    .append('path')
                    .attr('d', `M12.5 -12 v${orientation === ORIENTATION.VERTICAL ? 15 : 32}`)
                    .attr('class', 'employeesLine');

                // 员工列表
                const employeeBox = employeesNode
                    .append('g')
                    .attr('class', 'employeeBox')
                    .attr('display', employeeVisible ? 'block' : 'none')
                    .attr('transform', `translate(${0}, ${0})`);

                // 员工名称的下划线
                employeeBox
                    .selectAll('.employeeLine')
                    .data(combineEmployees)
                    .enter()
                    .append('path')
                    .attr('class', 'employeeItemLine')
                    .attr('d', (d, i) =>
                        orientation === ORIENTATION.VERTICAL || depth === 0
                            ? `M12.5 0 v${32 * (i + 1) + 26} h225`
                            : `M12.5 32 h120 v${32 * (i + 1) + 16} h225`
                    );

                const employeeForeignObject = employeeBox
                    .append('foreignObject')
                    .attr('x', orientation === ORIENTATION.VERTICAL || depth === 0 ? 0 : 120)
                    .attr('y', orientation === ORIENTATION.VERTICAL ? 30 : 52)
                    .attr('width', 225)
                    .attr('height', combineEmployees.length * 32);

                // 员工列表
                employeeForeignObject
                    .selectAll('.employeeBoxWrapper')
                    .data(combineEmployees)
                    .enter()
                    .append('xhtml:div')
                    .attr('class', 'employeeItem')
                    .append('xhtml:span')
                    .attr('class', 'employeeItemInfo')
                    .html(
                        d =>
                            // ${d.rankValue ? `/${d.rankValue}`
                            // <small
                            //     className="employeeItemRank ${!isShowModal && 'disabled'}"
                            //     data-rank-code="${d.rankCode}"
                            // >
                            //     ${d.rankValue ? `/${d.rankValue}` : ''}
                            // </small>
                            `<span class="employeeItemInfoBox" title="${d.employeeName} ${d.dutyAlias || ''} ${
                                d?.auditStatus === 1 ? ' 审批中' : ''
                            }">
                                <i style="background-image:url(${d?.avatarFile[0]?.url || defaultAvatar})"></i>
                                <strong class="employeeItemName ${d?.employeeCode ? '' : 'noEmployeeName'} ${
                                !isShowModal ? 'disabled' : ''
                            }"
                                    data-employee-code="${d?.employeeCode}"
                                    data-organization-code="${organizationCode}"
                                    data-organization-type="${organizationType}"
                                    data-organization-permissions="${organizationPermissions}"
                                    style="color: ${getNodeColorCode(d)};"
                                >
                                    ${d.employeeName}
                                </strong>
                                <span>
                                    <small class="employeeItemDuty ${!isShowModal ? 'disabled' : ''}" data-duty-code="${
                                d.dutyCode
                            }">
                                      ${d.dutyAlias || ''}
                                    </small>
                                    ${d?.auditStatus === 1 ? '<small class="auditStatus">审批中</small>' : ''}
                                </span>
                            </span>`
                    );

                // +-符号的事件
                const foreignObject = employeesNode
                    .append('foreignObject')
                    .attr('x', 0)
                    .attr('y', orientation === ORIENTATION.VERTICAL ? 0 : 20)
                    .attr('width', 25)
                    .attr('height', 25);

                foreignObject
                    .append('xhtml:div')
                    .attr('class', 'employeesShape')
                    .on('dblclick', () => {
                        d3.event.stopPropagation();
                    })
                    .on('click', () => {
                        d3.event.stopPropagation();
                        onCollapseEmployeesNode(nodeData, !employeeVisible);
                    })
                    .append('xhtml:span')
                    .attr('class', 'shape')
                    .attr('data-visible', employeeVisible)
                    .text(employeeVisible ? '-' : '+');
            }

            if (!hasChildren && combineEmployees.length > 0) {
                const employeesNode = svg
                    .insert('g', '.nodeBase')
                    .attr('class', 'employeesNode')
                    .attr('data-employees-id', organizationCode)
                    .attr(
                        'transform',
                        `translate(${orientation === ORIENTATION.VERTICAL ? x - 14.5 : y + NODE_SIZE.x / 2 + 13}, ${
                            orientation === ORIENTATION.VERTICAL ? y : x - 14.5
                        })`
                    );

                // 链接+-符号的左侧线
                employeesNode
                    .append('path')
                    .attr('d', `${orientation === ORIENTATION.VERTICAL ? 'M12.5 -12 v15' : 'M-20 13 h20'}`)
                    .attr('class', 'employeesLine');

                const employeeBox = employeesNode
                    .append('g')
                    .attr('class', 'employeeBox')
                    .attr('display', employeeVisible ? 'block' : 'none')
                    .attr('transform', `translate(${0}, ${0})`);

                employeeBox
                    .append('path')
                    .attr('class', 'employeeItemBox')
                    .attr('d', () =>
                        orientation === ORIENTATION.VERTICAL
                            ? `M12.5 0 v42 h-122 v${combineEmployees.length * 32} h250 v-${combineEmployees.length *
                                  32} h-127`
                            : `M12.5 12.5 h42 v${(combineEmployees.length * 32) / 2} h250 v-${combineEmployees.length *
                                  32} h-250 v${(combineEmployees.length * 32) / 2}`
                    );

                employeeBox
                    .selectAll('.employeeLine')
                    .data(combineEmployees)
                    .enter()
                    .append('path')
                    .attr('class', 'employeeItemBoxLine')
                    .attr('d', (d, i) =>
                        orientation === ORIENTATION.VERTICAL
                            ? `M-110 ${32 * i + 43 + 32} h${i >= combineEmployees.length - 1 ? 0 : 250}`
                            : `M54.5 ${-(combineEmployees.length * 32) / 2 + 12.5 + 32 * (i + 1)} h${
                                  i >= combineEmployees.length - 1 ? 0 : 250
                              }`
                    );

                const employeeForeignObject = employeeBox
                    .append('foreignObject')
                    .attr('x', orientation === ORIENTATION.VERTICAL ? -108 : 56)
                    .attr('y', orientation === ORIENTATION.VERTICAL ? 43 : -((combineEmployees.length * 32) / 2) + 12.5)
                    .attr('width', 247)
                    .attr('height', combineEmployees.length * 32);

                employeeForeignObject
                    .selectAll('.employeeBoxWrapper')
                    .data(combineEmployees)
                    .enter()
                    .append('xhtml:div')
                    .attr('class', 'employeeItem employeeBoxItem')
                    .append('xhtml:span')
                    .attr('class', 'employeeItemInfo')
                    .html(
                        d =>
                            // ${d.rankValue ? `/${d.rankValue}`
                            // <small
                            //     className="employeeItemRank ${!isShowModal && 'disabled'}"
                            //     data-rank-code="${d.rankCode}"
                            // >
                            //     ${d.rankValue ? `/${d.rankValue}` : ''}
                            // </small>
                            `<span class="employeeItemInfoBox" title="${d.employeeName} ${d.dutyAlias || ''} ${
                                d?.auditStatus === 1 ? ' 审批中' : ''
                            }">
                                <i style="background-image:url(${d?.avatarFile[0]?.url || defaultAvatar})"></i>
                                <strong class="employeeItemName ${d?.employeeCode ? '' : 'noEmployeeName'} ${
                                !isShowModal ? 'disabled' : ''
                            }"
                                    data-employee-code="${d?.employeeCode}"
                                    data-organization-code="${organizationCode}"
                                    data-organization-type="${organizationType}"
                                    data-organization-permissions="${organizationPermissions}"
                                    style="color: ${getNodeColorCode(d)};"
                                >
                                    ${d.employeeName}
                                </strong>
                                <span>
                                    <small class="employeeItemDuty ${!isShowModal ? 'disabled' : ''}" data-duty-code="${
                                d.dutyCode
                            }">
                                    ${d.dutyAlias || ''}
                                    </small>
                                    ${d?.auditStatus === 1 ? '<small class="auditStatus">审批中</small>' : ''}
                                </span>
                            </span>`
                    );

                // +-符号的事件
                const foreignObject = employeesNode
                    .append('foreignObject')
                    .attr('x', 0)
                    .attr('y', 0)
                    .attr('width', 25)
                    .attr('height', 25);

                foreignObject
                    .append('xhtml:div')
                    .attr('class', 'employeesShape')
                    .on('dblclick', () => {
                        d3.event.stopPropagation();
                    })
                    .on('click', () => {
                        d3.event.stopPropagation();
                        onCollapseEmployeesNode(nodeData, !employeeVisible);
                    })
                    .append('xhtml:span')
                    .attr('class', 'shape')
                    .attr('data-visible', employeeVisible)
                    .text(employeeVisible ? '-' : '+');
            }
        };

        if (organizationPath) {
            drawRootLine();
            drawDasharrayLine();
            drawAgentManagementLine();
            drawNodeShape();
            if (!onlyTree) {
                // 非审批阶段
                drawEmployees().then();
            }
        }
    });

    const handleDelete = () => {
        const confirmModal = Modal.confirm({
            title: '确定删除？',
            icon: <Icon type="close-circle" theme="filled" style={{ color: 'red' }} />,
            okText: '确认',
            cancelText: '取消',
            okButtonProps: {
                disabled: organizationType === 3
            },
            content: (
                <>
                    {organizationType === 3 ? (
                        <div className={styles.deleteInfo}>
                            <p>删除此机构前请先确认：</p>
                            <p>· 此机构下是否有在职员工？</p>
                            <p>· 此机构下是否有岗位正在招聘？</p>
                            <p>· 此机构下是否有正在入职的员工？</p>
                            <p>上述情况皆无，才能够删除此机构</p>
                            <div>
                                <Checkbox
                                    onChange={e => {
                                        confirmModal.update({
                                            okButtonProps: {
                                                disabled: !e.target.checked
                                            }
                                        });
                                    }}
                                >
                                    确认删除此机构
                                </Checkbox>
                            </div>
                        </div>
                    ) : (
                        `删除${organizationTypeDict[organizationType]}将无法恢复，确定删除吗？`
                    )}
                </>
            ),
            onOk: async () => {
                if (nodeData.data.append) {
                    onDelete(nodeData, nodeData.data);
                } else {
                    // 删除前校验
                    const { msg, code: responseCode } = await orgDeleteCheck({ organizationCode });
                    if (responseCode === 10000) {
                        onDelete(nodeData, nodeData.data);
                    } else {
                        Modal.error({
                            title: '删除失败',
                            icon: <Icon type="close-circle" theme="filled" style={{ color: 'red' }} />,
                            content: msg,
                            okText: '我知道了'
                        });
                    }
                }
            }
        });
    };

    // 折叠左侧节点
    const handleLeftNodeCollapse = () => {
        if (leftNode) {
            onCollapseLeftNode(nodeData, !leftNode.hidden);
        }
    };

    // 折叠右侧节点
    const handleRightNodeCollapse = () => {
        if (rightNode) {
            onCollapseRightNode(nodeData, !rightNode.hidden);
        }
    };

    const handleVisibleOrganizationModal = () => {
        if (!onlyTree && !control && organizationCode) {
            onClickOrganizationModal(organizationCode);
            // Modal.info({
            //     icon: null,
            //     maskClosable: true,
            //     title: organizationName,
            //     content: <Organization organizationCode={organizationCode} />,
            //     okText: '确定',
            //     okButtonProps: { style: { display: 'none' } }
            // });
        }
    };

    const auditStyle = useMemo(() => {
        if (deleted) {
            return 'deletedTip';
        }

        if (append) {
            return 'appendTip';
        }

        if (!(deleted || append) && auditStatus === 1) {
            return 'approveTip';
        }

        return '';
    }, [append, auditStatus, deleted]);

    // 是否显示卡片的操作栏
    const isShowCardControls =
        control &&
        !deleted &&
        organizationPermissions !== 0 &&
        (checkCode('office:orgs:organization:new') ||
            checkCode('office:orgs:organization:new') ||
            checkCode('office:orgs:organization:delete'));

    if (!organizationPath) {
        return null;
    }

    const removeEmployeePopover = () => {
        // 阻塞进程，渲染之后再删除
        setTimeout(() => {
            const employeePopover = document.querySelector('.employeePopover:not(.ant-popover-hidden)');
            const openedEmployeePopover = document.querySelector('.ant-popover-open');
            if (openedEmployeePopover) {
                openedEmployeePopover.classList.remove('ant-popover-open');
            }
            if (employeePopover) {
                employeePopover.classList.add('ant-popover-hidden');
            }
        }, 0);
    };

    const handleDutyClick = (e, dutyCode) => {
        e.stopPropagation();
        eventTrack({
            eventName: 'personnel_management_organization_view_context_click',
            pageName: 'personnel_management_organization',
            eventProps: {
                click_context: `${`${organizationName}-${leaderEmployees?.[0]?.employeeName}`} 岗位职责`
            }
        });
        removeEmployeePopover();
        onClickJobDuty(dutyCode);
    };

    // const handleRankClick = (e, rankCode) => {
    //     e.stopPropagation();
    //     eventTrack({
    //         eventName: 'personnel_management_organization_view_context_click',
    //         pageName: 'personnel_management_organization',
    //         eventProps: {
    //             click_context: `${`${organizationName}-${leaderEmployees?.[0]?.employeeName}`} 职级描述`
    //         }
    //     });
    //     removeEmployeePopover();
    //     onClickJobRank(rankCode);
    // };

    return depth === 0 ? (
        <div
            key={organizationPath}
            className={`nodeWrapper${orientation === ORIENTATION.HORIZONTAL ? ' orgHorizontal' : ''}`}
            onClick={e => e.stopPropagation()}
            data-org-path={organizationPath}
            data-org-code={organizationCode}
            data-org-name={organizationName}
            data-x={x}
            data-y={y}
            data-depth={depth}
        >
            <div className="nodeCard groupNode rootNode">
                <div className="leftControl" />
                <div className="nodeContentBox">
                    <div className={styles.nodeOrgName}>
                        <span
                            className={cn(styles.name, !isShowModal ? styles.nameDisabled : null)}
                            title={organizationName}
                            onClick={handleVisibleOrganizationModal}
                        >
                            {organizationName}
                        </span>
                    </div>
                </div>
                <div className="rightControl" />
            </div>
        </div>
    ) : (
        <div
            key={organizationPath}
            className={`nodeWrapper${orientation === ORIENTATION.HORIZONTAL ? ' orgHorizontal' : ''}`}
            onClick={e => e.stopPropagation()}
            data-org-path={organizationPath}
            data-org-code={organizationCode}
            data-org-name={organizationName}
            data-x={x}
            data-y={y}
            data-depth={depth}
        >
            <div className={`nodeCard ${['', 'groupNode', 'companyNode', 'departmentNode'][organizationType]}`}>
                <div className="leftControl">
                    {leftNode && leftNode.hidden && (
                        <>
                            <span className="leftCollapse plus" onClick={handleLeftNodeCollapse}>
                                <Icon type="plus" />
                            </span>
                            <i className="controlLine" />
                        </>
                    )}
                    {leftNode && !leftNode.hidden && (
                        <>
                            <span className="leftCollapse minus" onClick={handleLeftNodeCollapse}>
                                <Icon type="minus" />
                            </span>
                            <i className="controlLine controlLineMinus" />
                        </>
                    )}
                    {!leftNode && <span className="placeholder">&nbsp;&nbsp;</span>}
                </div>
                <div className={`nodeContentBox ${auditStyle}`}>
                    <div className={styles.nodeOrgName}>
                        <i
                            className={styles.companySign}
                            style={{
                                backgroundColor: getNodeColorCode(leaderEmployees?.[0])
                            }}
                        />
                        <span
                            className={cn(styles.name, !isShowModal ? styles.nameDisabled : null)}
                            title={organizationName}
                            disabled={onlyTree}
                            onClick={handleVisibleOrganizationModal}
                        >
                            {organizationName}
                        </span>
                        {organizationType === 3 && (
                            <span className={styles.number}>
                                <Icon type="team" style={{ fontSize: 14 }} />
                                {allEmployeeNum}
                                {/* {employeeNum} */}
                            </span>
                        )}
                        <Divider type="vertical" />
                        <span className={styles.focus} onClick={() => onFocusNode(nodeData)}>
                            <Icon type="fullscreen-exit" />
                        </span>
                    </div>

                    <div className={`${styles.employeesWrapper}${isShowCardControls ? ' employeesBox' : ''}`}>
                        {/* 无主管数据, 类型是部门, 非审批的场景 */}
                        {leaderEmployees.filter(item => item.showStatus !== -1001)?.length === 0 &&
                            organizationType === 3 &&
                            !onlyTree && (
                                <div className={styles.noEmployeeLeader}>
                                    <Avatar size={22} />
                                    <Text disabled className={styles.noEmployeeName}>
                                        暂无主管
                                        {leaderDutyAuditStatus === 2 ? (
                                            <span style={{ marginLeft: 8 }}>{leaderDutyAlias}</span>
                                        ) : null}
                                    </Text>
                                </div>
                            )}

                        {leaderEmployees
                            .filter(item => item.showStatus !== -1001)
                            .map((employee, index) => {
                                const {
                                    avatarFile,
                                    employeeName,
                                    employeeCode,
                                    dutyAlias,
                                    // rankValue,
                                    dutyCode
                                    // rankCode
                                } = employee;
                                if (index < 1 && !onlyTree) {
                                    return (
                                        <div className={styles.nodeOrgPrincipal} key={employee}>
                                            <span className={styles.avatar}>
                                                <Avatar src={avatarFile[0]?.url} alt={employeeName} size={22} />
                                            </span>
                                            <span
                                                className={cn(
                                                    'employeeItemName',
                                                    styles.name,
                                                    !isShowModal ? 'disabled' : ''
                                                )}
                                                title={employeeName}
                                                style={{
                                                    color: getNodeColorCode(employee),
                                                    cursor: employeeCode && isShowModal ? 'pointer' : 'not-allowed'
                                                }}
                                                data-employee-code={employeeCode}
                                                data-organization-code={organizationCode}
                                                data-organization-type={organizationType}
                                                data-organization-permissions={organizationPermissions}
                                                disabled={!isShowModal}
                                            >
                                                {employeeName}
                                            </span>
                                            <span className={styles.jobGrade}>
                                                {dutyAlias && (
                                                    <span
                                                        className={cn(styles.dutyAlias, !isShowModal ? 'disabled' : '')}
                                                        title={dutyAlias}
                                                        onClick={e => isShowModal && handleDutyClick(e, dutyCode)}
                                                    >
                                                        {dutyAlias}
                                                    </span>
                                                )}
                                                {/* {dutyAlias && rankValue && '/'} */}
                                                {/* {rankValue && ( */}
                                                {/*    <span */}
                                                {/* className={cn(styles.rankValue, !isShowModal && 'disabled')} */}
                                                {/* onClick={e => isShowModal && handleRankClick(e, rankCode)} */}
                                                {/* title={rankValue} */}
                                                {/*    > */}
                                                {/*        {rankValue} */}
                                                {/*    </span> */}
                                                {/* )} */}
                                            </span>
                                        </div>
                                    );
                                }
                                return null;
                            })}
                    </div>

                    {isShowCardControls && (
                        <div className="operateBar">
                            <span>
                                {checkCode('office:orgs:organization:new') && (
                                    <i
                                        className={cn('iconfont iconlistfunction_addcompany_icon_default')}
                                        disabled={
                                            organizationType === 3 || (auditStatus !== undefined && auditStatus !== 2)
                                        }
                                        title="新增公司"
                                        onClick={() => {
                                            modalRef.current.addCompany(nodeData.data, values => {
                                                onAddCompany(nodeData, {
                                                    organizationPath: `path${Math.floor(
                                                        Math.random() * 1000000000000000000
                                                    )}`,
                                                    organizationType: 2,
                                                    parentOrganizationPath: organizationPath,
                                                    append: true,
                                                    ...values
                                                });
                                            });
                                        }}
                                    />
                                )}
                                {checkCode('office:orgs:organization:new') && (
                                    <i
                                        className={cn('iconfont iconlistfunction_adddepartment_icon_default')}
                                        disabled={
                                            organizationType === 2 || (auditStatus !== undefined && auditStatus !== 2)
                                        }
                                        title="新增部门"
                                        onClick={() => {
                                            // 这里处理了是否展示部门编辑的时候顶部那一条提示
                                            // 如果children为空，显示 如果childer不为空并且其中一个部门审核通过则不显示.
                                            // 如果下级部门都在审批中，一个或者多个，没有审批通过的，则显示
                                            const { _children } = nodeData;
                                            if (_children === '' || _children === undefined) {
                                                setShowTips(true);
                                            }
                                            if (_children && _children.length > 0) {
                                                if (_children?.some(item => item?.data?.auditStatus === 1)) {
                                                    setShowTips(true);
                                                }
                                                if (_children?.some(item => item?.data?.auditStatus === 2)) {
                                                    setShowTips(false);
                                                }
                                            }
                                            modalRef.current.addDepartment(nodeData.data, values => {
                                                onAddDepartment(nodeData, {
                                                    organizationPath: `path${Math.floor(
                                                        Math.random() * 1000000000000000000
                                                    )}`,
                                                    organizationType: 3,
                                                    parentOrganizationPath: organizationPath,
                                                    append: true,
                                                    ...values
                                                    // titleName: values.supervisorName.label,
                                                    // titleValue: values.supervisorName.key
                                                });
                                            });
                                        }}
                                    />
                                )}
                            </span>
                            <span>
                                {checkCode('office:orgs:organization:delete') &&
                                    auditStatus !== 1 &&
                                    organizationType !== 1 && (
                                        <i
                                            disabled={
                                                auditStatus !== 2 ||
                                                organizationType === 1 ||
                                                leaderEmployees.find(item => item.showStatus < 0)
                                            }
                                            title="删除"
                                            className={cn('iconfont iconlistfunction_delete_icon_default')}
                                            onClick={handleDelete}
                                        />
                                    )}
                            </span>
                        </div>
                    )}
                </div>
                <div className="rightControl">
                    {rightNode && rightNode.hidden && (
                        <>
                            <i className="controlLine" />
                            <span className="rightCollapse plus" onClick={handleRightNodeCollapse}>
                                <Icon type="plus" />
                            </span>
                        </>
                    )}
                    {rightNode && !rightNode.hidden && (
                        <>
                            <i className="controlLine controlLineMinus" />
                            <span className="rightCollapse minus" onClick={handleRightNodeCollapse}>
                                <Icon type="minus" />
                            </span>
                        </>
                    )}
                    {!rightNode && <span className="placeholder">&nbsp;&nbsp;</span>}
                </div>
            </div>

            <OrganizationModal wrappedComponentRef={modalRef} showTips={showTips} setShowTips={setShowTips} />
        </div>
    );
};

Node.propTypes = {
    nodeData: PropTypes.object,
    control: PropTypes.bool,
    onAddCompany: PropTypes.func.isRequired,
    onAddDepartment: PropTypes.func.isRequired,
    onDelete: PropTypes.func.isRequired,
    onCollapseEmployeesNode: PropTypes.func.isRequired,
    onCollapseLeftNode: PropTypes.func.isRequired,
    onCollapseRightNode: PropTypes.func.isRequired
};

Node.defaultProps = {
    nodeData: {},
    control: false
};
export default Node;
